package com.yimi.yinhepda.views.load_module

import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.view.View
import com.jzxiang.pickerview.TimePickerDialog
import com.jzxiang.pickerview.data.Type
import com.pda.uce.commom.pickerview.builder.OptionsPickerBuilder
import com.pda.uce.commom.pickerview.listener.OnOptionsSelectListener
import com.pda.uce.commom.util.MyDialog
import com.pda.ym.base.BaseTitleActivity
import com.pda.ym.callbacks.UICallBack
import com.pda.ym.db.table.CarPlateTable
import com.pda.ym.net.NetRequest
import com.pda.ym.utils.CarNoSelectDialog
import com.pda.ym.utils.Constants
import com.pda.ym.utils.DateHelper
import com.pda.ym.utils.SoundVibratorManager
import com.uce.pda.MyAppLication
import com.uce.pda.bean.Trans
import com.uce.pda.util.ArrayUtils
import com.yimi.yinhepda.R
import com.yimi.yinhepda.callbacks.OnClickCallBack
import com.yimi.yinhepda.db.dao.CarPlateTableDao
import com.yimi.yinhepda.db.dao.DepartmentTableDao
import com.yimi.yinhepda.entity.bean.CheckBoxItemEntity
import com.yimi.yinhepda.entity.bean.LoaderEntity
import com.yimi.yinhepda.entity.request.QueryLoadTaskV2Request
import com.yimi.yinhepda.entity.response.QueryLoadTaskV2Response
import com.yimi.yinhepda.entity.response.QueryVehicleAttributeResponse
import com.yimi.yinhepda.event.CreateStowagesEvent
import com.yimi.yinhepda.utils.Common
import com.yimi.yinhepda.utils.DialogUtil
import com.yimi.yinhepda.utils.TransInformation
import kotlinx.android.synthetic.main.activity_create_branch_task.*
import kotlinx.android.synthetic.main.layout_select_shit.*
import kotlinx.android.synthetic.main.select_car_plate.*
import kotlinx.android.synthetic.main.view_create_task_type.*
import org.greenrobot.eventbus.EventBus
import rx.Observable
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.*

/**
 * @author: lj
 * Date: 2020/4/10 16:31
 * Description: 融合 创建支线任务
 */
class CreateBranchTaskActivity : BaseTitleActivity(true) {

    companion object {
        const val LOAD_KEY = "loadType"
        //装车创建支线任务标识
        const val LOAD_TYPE = 1
        //创建卸车任务标识
        const val UNLOAD_TYPE = 2
    }

    //运输方式选项
    private var isOptions1Trans = 0
    //班次选项
    private var isOptions1 = 0
    //班次数据
    private lateinit var mShiftList: MutableList<String>
    //下一站/上一站集合
    private var mDataList: MutableList<CheckBoxItemEntity>? = null
    //装卸车类型：1-装车，2-卸车
    private var mLoadType = 0
    //已选择的下一站集合
    private var mSelectList: MutableList<CheckBoxItemEntity>? = null
    private val mDeptDao by lazy { DepartmentTableDao() }
    //创建的支线任务
    private val mCreateStowageNos by lazy { mutableListOf<String>() }

    override fun getPageName(): String {
        return "创建支线任务"
    }

    override fun showBack(): Boolean {
        return false
    }

    override fun setBack() {
    }

    override fun setTitle(): String {
        return pageName
    }

    override fun setContentViewId(): Int {
        return R.layout.activity_create_branch_task
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        btn_carPlate.setOnClickListener(this)
        tv_trans_type.setOnClickListener(this)
        tv_date.setOnClickListener(this)
        tv_shift.setOnClickListener(this)
        btn_back.setOnClickListener(this)
        btn_create.setOnClickListener(this)
        ll_select_nextDept.setOnClickListener(this)

        //初始设置车牌
        val carPlateTables: List<CarPlateTable> = CarPlateTableDao().getAllData()
        if (!carPlateTables.isNullOrEmpty()) {
            btn_carPlate.text = carPlateTables[0].carPlate
        }

        et_carNo.transformationMethod = TransInformation()

        mShiftList = mutableListOf()
        mShiftList.add("01")
        mShiftList.add("02")
        mShiftList.add("03")
        mShiftList.add("04")
        mShiftList.add("05")
        mShiftList.add("06")
        mShiftList.add("07")
        mShiftList.add("08")
        mShiftList.add("09")
        mShiftList.add("10")


        ll_taskNo.visibility = View.GONE
        inc_carNo.visibility = View.GONE
        inc_shit.visibility = View.GONE

        tv_date.text = DateHelper.getDateFormate(Date())
        tv_shift.text = mShiftList[0]

        mLoadType = intent.getIntExtra(LOAD_KEY, 0)
        if (mLoadType == LOAD_TYPE) {
            //装车
            inc_carNo.visibility = View.VISIBLE
            inc_shit.visibility = View.VISIBLE
            ll_cb_taskType.visibility = View.VISIBLE
            //查询网点类型
            val departmentTable = DepartmentTableDao().queryDeptByDeptCode(sharedPreferUtil.deptCode)
            if (departmentTable != null) {
                when (departmentTable.isOmg) {
                    0 -> {
                        cb_ym.isChecked = true
                        cb_uc.isChecked = false
                    }
                    1 -> {
                        cb_ym.isChecked = false
                        cb_uc.isChecked = true
                    }
                    else -> {
                        cb_ym.isChecked = true
                        cb_uc.isChecked = true
                    }
                }
            }
            //查询本地下一站
            queryNextStation(false)
        } else if (mLoadType == UNLOAD_TYPE) {
            //卸车
            ll_taskNo.visibility = View.VISIBLE
            ll_cb_taskType.visibility = View.GONE
            tv_selStation.text = "上一站："
            queryPreviousStation(false)
            setTitle("创建卸车任务")
        }

        //运输方式默认选择 汽运
        if (!ArrayUtils.isEmpty(MyAppLication.transArrayList)) {
            for ((index, trans) in MyAppLication.transArrayList.withIndex()) {
                if (trans.TYPE_REMARK == "汽运") {
                    tv_trans_type.text = trans.TYPE_REMARK
                    tv_trans_type.tag = trans.SYS_CFG_KEY
                    isOptions1Trans = index
                }
            }
        }
    }

    override fun handleBarCode(result: String?) {
        et_taskNo.setText(result)
        SoundVibratorManager.playSound(1)
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v?.id) {
            R.id.ll_select_nextDept -> {
                //下一站/上一站
                if (mLoadType == LOAD_TYPE) {
                    //装车
                    if (mDataList.isNullOrEmpty()) {
                        queryNextStation(true)
                    } else {
                        showSelectDeptDialog(Constants.PLEASE_SELECT_NEXT_DEPT)
                    }
                } else if (mLoadType == UNLOAD_TYPE) {
                    //卸车
                    if (mDataList.isNullOrEmpty()) {
                        queryPreviousStation(true)
                    } else {
                        showSelectDeptDialog(Constants.PLEASE_SELECT_PREV_DEPT)
                    }
                }
            }
            R.id.btn_carPlate -> {
                //省市车牌
                CarNoSelectDialog.showCarPlateDialog(this) { carPlate ->
                    btn_carPlate.text = carPlate
                }
            }
            R.id.tv_trans_type -> {
                //运输方式
                if (!ArrayUtils.isEmpty(MyAppLication.transArrayList)) {
                    val problemOptions = OptionsPickerBuilder(this,
                            OnOptionsSelectListener { options1, options2, options3, v ->
                                isOptions1Trans = options1
                                tv_trans_type.text = MyAppLication.transArrayList[options1].TYPE_REMARK
                                tv_trans_type.tag = MyAppLication.transArrayList[options1].SYS_CFG_KEY
                            }) //确定按钮文字
                            .setSubmitText("确定")
                            .setCancelText("取消")
                            .setSubmitColor(Color.BLACK)
                            .setCancelColor(Color.BLACK)
                            .setContentTextSize(20)
                            //循环与否
                            .setCyclic(false, false, false)
                            //设置默认选中项
                            .setSelectOptions(isOptions1Trans)
                            .isDialog(false)
                            .build<Trans>()
                    //添加数据源
                    problemOptions.setPicker(MyAppLication.transArrayList)
                    problemOptions.show()
                } else {
                    showToast("未获取到运输方式！")
                }
            }
            R.id.tv_date -> {
                //班次日期
                val clockDate = DateHelper.getDateFormate(Date())
                //获得选择日期的当前时间戳
                val selectTextTime = DateHelper.getDate(clockDate).time
                val timePickerDialog = TimePickerDialog.Builder().setCallBack { timePickerView, millseconds ->
                    var time = DateHelper.getDateToString(millseconds, DateHelper.dateFormat)
                    if (time.length > 9) {
                        time = time.substring(0, 10)
                    }
                    tv_date.text = time
                }
                        .setCancelStringId("取消")
                        .setSureStringId("确定")
                        .setTitleStringId("选择")
                        .setYearText("年")
                        .setMonthText("月")
                        .setDayText("日")
                        .setCyclic(false)
                        //设置能获取的最小值getMills（）是获取时间毫秒值
                        .setMinMillseconds(DateHelper.getDifferenceTime(0))
                        //设置能到达的最大值
//                        .setMaxMillseconds(System.currentTimeMillis())
                        //设置当前时间
                        .setCurrentMillseconds(selectTextTime)
                        .setThemeColor(resources.getColor(R.color.timepicker_dialog_bg))
                        .setType(Type.YEAR_MONTH_DAY)
                        .setWheelItemTextNormalColor(resources.getColor(R.color.timepicker_dialog_bg))
                        .setWheelItemTextSelectorColor(resources.getColor(R.color.timepicker_toolbar_bg))
                        .setWheelItemTextSize(12)
                        .build()
                timePickerDialog.show(supportFragmentManager, "YEAR_MONTH_DAY")
            }
            R.id.tv_shift -> {
                //班次号
                val problemOptions = OptionsPickerBuilder(this,
                        OnOptionsSelectListener { options1, options2, options3, v ->
                            isOptions1 = options1
                            tv_shift.text = mShiftList[options1]
                        }) //确定按钮文字
                        .setSubmitText("确定") //取消按钮文字
                        .setCancelText("取消") //确定按钮文字颜色
                        .setSubmitColor(Color.BLACK) //取消按钮文字颜色
                        .setCancelColor(Color.BLACK) //滚轮文字大小
                        .setContentTextSize(20) //循环与否
                        .setCyclic(false, false, false) //设置默认选中项
                        .setSelectOptions(isOptions1) //是否显示为对话框样式
                        .isDialog(false)
                        .build<String>()
                //添加数据源
                problemOptions.setPicker(mShiftList)
                problemOptions.show()
            }
            R.id.btn_back -> finish()
            R.id.btn_create -> {
                //创建
                if (mLoadType == LOAD_TYPE) {
                    //装车
                    startLoadTask()
                } else if (mLoadType == UNLOAD_TYPE) {
                    //卸车
                    createUnLoad()
                }
            }
        }
    }

    /**
     * 创建装车任务
     */
    private fun startLoadTask() {

        if (!cb_ym.isChecked && !cb_uc.isChecked) {
            SoundVibratorManager.playSound(2)
            showToast("请至少选择一个任务类型！")
            return
        }

        if (tv_nextDeptName.text.toString() == "") {
            SoundVibratorManager.playSound(2)
            showToast("请选择下一站！")
            return
        }

        mCreateStowageNos.clear()

        queryStowageTask(0, 1)
    }

    /**
     * 创建配载单/发件任务/到件任务
     * @param index 遍历多个上下一站 索引
     * @param taskType 1-出发创建，2-到达创建
     */
    private fun queryStowageTask(index: Int, taskType: Int) {

        val carPlate = btn_carPlate.text.toString()
        val carNo = et_carNo.text.toString().toUpperCase()

        if (index > mSelectList!!.size - 1) {
            dismissPgDlg()
            showToast("创建成功")
            finish()

            val event = CreateStowagesEvent()
            event.carNo = carPlate + carNo
            event.stowageNos = mCreateStowageNos
            event.nextDeptCode = mSelectList!![0].code
            event.nextDeptCodeName = mSelectList!![0].name
            EventBus.getDefault().post(event)

            return
        }

        if (taskType == 1) {
            //校验当前部门或者下一部门是否纯快递属性，是则车牌号和班次可不填写，直接请求创建快递发件任务
//            val currentDept = mDeptDao.queryDeptByDeptCode(sharedPreferUtil.deptCode)
//            val nextDept = mDeptDao.queryDeptByDeptCode(mSelectList!![index].code)
//            if (currentDept != null && nextDept != null) {
//                if (currentDept.isOmg == 1 || nextDept.isOmg == 1) {
//                    //纯快递属性直接请求创建发件任务
//                    createLoadTask(index, taskType)
//                    return
//                }
//            }
            if (!cb_ym.isChecked && cb_uc.isChecked) {
                //纯快递属性直接请求创建发件任务
                createLoadTask(index, taskType)
                return
            }
            if (cb_ym.isChecked) {
                if (carPlate == "" || carNo == "") {
                    SoundVibratorManager.playSound(2)
                    showToast("请输入车牌号！")
                    return
                }
                if (tv_date.text.toString() == "" || tv_shift.text.toString() == "") {
                    SoundVibratorManager.playSound(2)
                    showToast("请选择班次！")
                    return
                }
            }
            queryCarAttribute(carPlate + carNo, index, taskType)
        } else {
            //干线强制输入任务号
            val deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE)
            val prevDept = mDeptDao.queryDeptByDeptCode(mSelectList!![index].code)
            if ((deptType == 5 || deptType == 6) && (prevDept?.deptType == 5 || prevDept?.deptType == 6)) {
                if (et_taskNo.text.toString() == "") {
                    showToast("上一站(${prevDept.deptName})为干线，需输入任务号！")
                    return
                }
            }
            createLoadTask(index, taskType)
        }
    }

    /**
     * 查询车辆属性，为自有车辆不允许创建支线
     * @param index 遍历多个上下一站 索引
     * @param taskType 1-出发创建，2-到达创建
     */
    private fun queryCarAttribute(carNo: String, index: Int, taskType: Int) {
        showPgDlg("查询车辆信息中...")
        val params: MutableMap<String, String> = HashMap(1)
        params["vehNo"] = carNo
        NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(Constants.URL_QUERY_CAR_ATTRIBUTE)
                .setParams(params)
                .setResponsClazz(QueryVehicleAttributeResponse::class.java)
                .execute(object : UICallBack() {
                    override fun onError(msg: String) {
                        dismissPgDlg()
                        if (Constants.RETURN_MESSAGE_IS_NULL.equals(msg)){
                            showToast("未查询到车辆信息！请联系调度维护！");
                        }
                        else{
                            showToast(String.format("查询车辆信息：%s", msg))
                        }

                    }

                    override fun onSuccess(obj: Any) {
                        val response = obj as QueryVehicleAttributeResponse
                        if (response.data != null) {
                            val entity = response.data
                            if (entity != null && entity.useType == 7) {
                                //自有运力不允许创建配载单
                                MyDialog.showAlertDialog(this@CreateBranchTaskActivity, "自有车辆不可创建任务！")
                                dismissPgDlg()
                            } else {
                                //非自有运力，继续创建支线任务
                                createLoadTask(index, taskType)
                            }
                        } else {
                            showToast("查询车辆信息为空！")
                            SoundVibratorManager.playSound(2)
                            dismissPgDlg()
                        }
                    }
                })
    }

    /**
     * 创建支线装车任务
     * @param index 遍历多个上下一站 索引
     * @param taskType 1-出发创建，2-到达创建
     */
    private fun createLoadTask(index: Int, taskType: Int) {
        val request = QueryLoadTaskV2Request()
        request.stowageSource = 6
        request.source = 6
        request.scheduleNo = tv_date.text.toString() + tv_shift.text.toString()
        request.srcDeptCode = sharedPreferUtil.deptCode
        request.srcDeptName = sharedPreferUtil.getValue(Common.DEPT_NAME)
        request.destDeptCode = mSelectList!![index].code
        request.destDeptName = mSelectList!![index].name
        if (et_carNo.text.toString() != "") {
            request.carNo = btn_carPlate.text.toString() + et_carNo.text.toString().toUpperCase()
        }
        request.taskType = taskType
        if (taskType == 2) {
            //卸车创建快递任务
            request.taskNo = et_taskNo.text.toString()
            request.createType = 2
        } else {
            //选择创建任务类型
            if (cb_ym.isChecked && cb_uc.isChecked) {
                request.createType = 0
            } else if (cb_ym.isChecked) {
                request.createType = 1
            } else {
                request.createType = 2
            }
        }
        val loaders = mutableListOf<LoaderEntity>()
        val loaderEntity = LoaderEntity()
        loaderEntity.empCode = sharedPreferUtil.getValue(Common.USER_CODE)
        loaderEntity.empName = sharedPreferUtil.empName
        loaderEntity.isLeader = 1
        loaders.add(loaderEntity)
        request.addLoaders = loaders
        showPgDlg("创建中...${index + 1}/${mSelectList!!.size}")
        NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setUrl(Constants.URL_V2_CREATE_STOWAGE_TASK)
                .setRequestObject(request)
                .setResponsClazz(QueryLoadTaskV2Response::class.java)
                .execute(object : UICallBack() {
                    override fun onError(msg: String) {
                        dismissPgDlg()
                        showToast(msg)
                        SoundVibratorManager.playSound(2)
                    }

                    override fun onSuccess(obj: Any) {
                        val reponse = obj as QueryLoadTaskV2Response
                        if (reponse.data != null && !reponse.data.stowageNos.isNullOrEmpty()) {

                            Handler().postDelayed({

                                mCreateStowageNos.addAll(reponse.data.stowageNos)
                                queryStowageTask(index = index + 1, taskType = taskType)

                            }, 1000)

                        } else {
                            dismissPgDlg()
                            SoundVibratorManager.playSound(2)
                            showToast("创建任务响应为空！")
                        }
                    }
                })
    }


    /**
     * 创建卸车任务
     */
    private fun createUnLoad() {
        if (et_taskNo.text.toString() == "" && tv_nextDeptName.text.toString() == "") {
            showToast("请填写任务号或者上一站！")
            return
        }
        queryStowageTask(0, 2)
    }

    /**
     * 查询下一站
     */
    private fun queryNextStation(isClick: Boolean) {
        if (isClick) {
            showPgDlg("查询中...")
        }
        Observable.create<Void> { subscriber ->
            //下一站路由
            mDataList = Common.queryNextDeptLines()
            subscriber.onCompleted()
        }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(object : Subscriber<Void?>() {
            override fun onCompleted() {
                dismissPgDlg()
                if (!isClick) {
                    if (!mDataList.isNullOrEmpty()) {
                        tv_nextDeptName.text = mDataList!![0].name
                        mDataList!![0].isCheck = true
                        mDataList!![0].isTempCheck = true

                        if (mSelectList == null) {
                            mSelectList = mutableListOf()
                        }
                        //添加默认选择第一个下一站
                        mSelectList!!.add(mDataList!![0])
                    }
                } else {
                    //显示下一站对话框
                    showSelectDeptDialog(Constants.PLEASE_SELECT_NEXT_DEPT)
                }
            }

            override fun onError(throwable: Throwable) {
                dismissPgDlg()
            }

            override fun onNext(t: Void?) {}
        })
    }

    /**
     * 查询上一站
     */
    private fun queryPreviousStation(isClick: Boolean) {
        if (isClick) {
            showPgDlg("查询中...")
        }
        Observable.create<Void> { subscriber ->
            //上一站路由
            mDataList = Common.queryPreviousDeptLines()
            subscriber.onCompleted()
        }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(object : Subscriber<Void?>() {
            override fun onCompleted() {
                dismissPgDlg()
                if (!isClick) {
                    if (!mDataList.isNullOrEmpty()) {
                        tv_nextDeptName.text = mDataList!![0].name
                        mDataList!![0].isCheck = true
                        mDataList!![0].isTempCheck = true

                        if (mSelectList == null) {
                            mSelectList = mutableListOf()
                        }
                        //添加默认选择第一个下一站
                        mSelectList!!.add(mDataList!![0])
                    }
                } else {
                    //显示下一站/上一站对话框
                    showSelectDeptDialog(Constants.PLEASE_SELECT_PREV_DEPT)
                }
            }

            override fun onError(throwable: Throwable) {
                dismissPgDlg()
            }

            override fun onNext(t: Void?) {}
        })
    }

    /**
     * 显示下一站/上一站对话框
     */
    private fun showSelectDeptDialog(msg: String) {
        //下一站选择框
        DialogUtil.checkBoxDialog(this@CreateBranchTaskActivity, msg, "确定", "返回", mDataList, object : OnClickCallBack() {
            override fun onCancle() {
            }

            override fun onSure(obj: Any?, obj1: Any?) {
                mSelectList = obj as MutableList<CheckBoxItemEntity>
                if (!mSelectList.isNullOrEmpty()) {
                    var nextDepts = ""
                    mSelectList?.forEach {
                        nextDepts += it.name + "/"
                    }
                    tv_nextDeptName.text = nextDepts.substring(0, nextDepts.length - 1);
                } else {
                    tv_nextDeptName.text = ""
                }
            }
        })
    }
}